package com.example.lotterysystem.controller.handler;

import com.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//获取全局的异常
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e){
        //打错误日志
        log.error("ServiceException: " + e);
        //构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMsg());
    }

    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e){
        //打错误日志
        log.error("ControllerException: " + e);
        //构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMsg());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> exception(Exception e){
        //打错误日志
        log.error("Exception: " + e);
        //构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<?> exception(MethodArgumentNotValidException e){
        //打错误日志
        log.error("MethodArgumentNotValidException: " + e);
        //构造错误结果
        return CommonResult.error(GlobalErrorCodeConstants.PARAM_NOT_NULL);
    }


}
